import unittest

from django.http import HttpRequest, HttpResponse
from django.utils.functional import curry
from django.core.exceptions import SuspiciousOperation

from signedcookies import middleware

class SignedCookiesTestCase(unittest.TestCase):

    def setUp(self):
        self.middleware = middleware.SignedCookiesMiddleware()
        self.key, self.unsigned_value = 'key', 'value'
        self.signature = self.middleware.get_digest(self.key, self.unsigned_value)
        self.signed_value = '%s:%s' % (self.signature, self.unsigned_value)
        self.invalid_value = self.signed_value + 'invalid'

    def test_sign(self):
        "Make sure cookie values can be signed directly"
        signed_value = self.middleware.sign(self.key, self.unsigned_value)
        self.assertEqual(signed_value, self.signed_value)

    def test_unsign_valid_value(self):
        "Make sure cookie values can be unsigned directly"
        unsigned_value = self.middleware.unsign(self.key, self.signed_value)
        self.assertEqual(unsigned_value, self.unsigned_value)

    def test_unsign_invalid_value(self):
        "Make sure cookie values can be unsigned directly"
        unsign = curry(self.middleware.unsign, self.key, self.invalid_value)
        self.assertRaises(SuspiciousOperation, unsign)

    def test_unsigned_cookie(self):
        "Make sure process_request removes unsigned cookies"
        request = HttpRequest()
        request.COOKIES[self.key] = self.unsigned_value
        self.middleware.process_request(request)
        self.assert_(self.key not in request.COOKIES)

    def test_invalid_cookie(self):
        "Make sure process_request removes invalid cookies"
        request = HttpRequest()
        request.COOKIES[self.key] = self.invalid_value
        self.middleware.process_request(request)
        self.assert_(self.key not in request.COOKIES)

    def test_valid_cookie(self):
        "Make sure process_request removes signatures from valid cookies"
        request = HttpRequest()
        request.COOKIES[self.key] = self.signed_value
        self.middleware.process_request(request)
        self.assertEqual(request.COOKIES[self.key], self.unsigned_value)

    def test_set_cookie(self):
        "Make sure process_response signs cookies appropriately"
        response = HttpResponse()
        response.set_cookie(self.key, self.unsigned_value)
        self.middleware.process_response(HttpRequest(), response)
        self.assertEqual(response.cookies[self.key].value, self.signed_value)

    def test_delete_cookie(self):
        "Make sure process_response leaves deleted cookies alone"
        response = HttpResponse()
        response.delete_cookie(self.key)
        self.middleware.process_response(HttpRequest(), response)
        self.assertEqual(response.cookies[self.key].value, '')